﻿using System;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Text;
using Com.Fubei.OpenApi.Sdk.Extensions;

namespace Com.Fubei.OpenApi.Sdk.Utils
{
    /// <summary>
    /// Http请求封装类
    /// </summary>
    public static class HttpUtil
    {
        /// <summary>
        /// https
        /// </summary>
        static HttpUtil()
        {
            ServicePointManager.DefaultConnectionLimit = 200;
            ServicePointManager.ServerCertificateValidationCallback = (obj, certificate, chain, errors) => true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
        }
        
        /// <summary>
        /// 类型，json
        /// </summary>
        private const string MimeType = "application/json;charset=utf-8";
        /// <summary>
        /// 返回内容编码
        /// </summary>
        private const string ContentEncoding = "Content-Encoding";
        /// <summary>
        /// gzip编码
        /// </summary>
        private const string Gzip = "gzip";


        /// <summary>
        /// 创建Web请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private static HttpWebRequest CreateRequest(string url)
        {
            var request = WebRequest.Create(url);
            request.Proxy = null;
            request.Method = "POST";
            request.ContentType = MimeType;
            request.Timeout = (int) TimeSpan.FromSeconds(30).TotalMilliseconds;
            return (HttpWebRequest) request;
        }
        
        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="requestParam"></param>
        /// <returns></returns>
        public static string PostRequest(string url, object requestParam)
        {
            HttpWebRequest req = null;
            try
            {
                req = CreateRequest(url);
                // 发送请求
                using (var writer = new StreamWriter(req.GetRequestStream(), Encoding.UTF8))
                {
                    writer.Write(requestParam.SerializeAsJson());
                }
                // 获得请求
                var resp = req.GetResponse();
                // 读取请求，并转为字符串
                var strContent = ReadAsString(resp);
                return strContent;
            }
            finally
            {
                if (req != null) req.Abort();
            }
        }
        
        /// <summary>
        /// 读取WebResponse，并将返回内容转为字符串
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        private static string ReadAsString(WebResponse response)
        {
            var responseStream = response.GetResponseStream();
            if (responseStream == null)
            {
                return "";
            }
            
            // 判断数据是否进行压缩
            var header = response.Headers[ContentEncoding] ?? "";
            if (Gzip.Equals(header, StringComparison.InvariantCultureIgnoreCase))
            {
                var gzipStream = new GZipStream(responseStream, CompressionMode.Decompress, true);
                using (var reader = new StreamReader(gzipStream))
                {
                    return reader.ReadToEnd();
                }
            }
            using (var reader = new StreamReader(responseStream))
            {
                return reader.ReadToEnd();
            }
        }
    }
}